package com.kool.core.notify;


import com.kool.core.CoreConstants;
import com.kool.core.cache.KCache;
import com.kool.system.bean.SyUserInfoBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: tianhe
 * @create: 2018/12/04 20:15
 */
@Slf4j
@Component
@ServerEndpoint(value = "/notify/{user}")
public class NotifyServer {

    public static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap();

    @OnOpen
    public void open(Session session) {
        Map<String, String> pathParams = session.getPathParameters();
        String user = new String(Base64.getDecoder().decode(pathParams.get("user")));
        sessionMap.put(user, session);

        System.out.println("user:"+user);
        Map<String, List<String>> reqParams = session.getRequestParameterMap();
        System.out.println("reqParams" + reqParams);

        System.out.println("onOpen...");

        try {
            String id = session.getId();

            SyUserInfoBean userInfoBean = (SyUserInfoBean) KCache.get(CoreConstants.KCACHE_USER,user);
            String userName = userInfoBean!=null?userInfoBean.getSuiLoginName():user;
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            basic.sendText("您好， " + userName+"！");
        } catch (Exception e) {
            log.error("通信异常：", e);
        }
    }

    @OnClose
    public void close(Session session) {
        System.out.println("onClose...");
        String id = session.getId();

        System.out.println("id:" + id);
        Map<String, String> pathParams = session.getPathParameters();
        String user = new String(Base64.getDecoder().decode(pathParams.get("user")));
        sessionMap.remove(user);

    }

    @OnMessage
    public void message(Session session, String msg) {
        System.out.println("onSend...");
        Map<String, String> pathParams = session.getPathParameters();
        String user = new String(Base64.getDecoder().decode(pathParams.get("user")));
        try {
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            basic.sendText("client " + user + " say:" + msg);
        } catch (Exception e) {
            log.error("通信异常：", e);
        }

    }
}
